import java.util.LinkedList;
import java.util.Queue;

/**
 * 面试题28：对称的二叉树
 */
public class Offer_28 {
    /**
     * 方法二：递归
     */
    public boolean isSymmetric(TreeNode root) {
        return checkRecursion(root, root);
    }

    private boolean checkRecursion(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        }
        if (p == null || q == null) {
            return false;
        }
        return p.val == q.val && checkRecursion(p.left, q.right) && checkRecursion(p.right, q.left);
    }

    /**
     * 方法一：循环
     */
    public boolean isSymmetric1(TreeNode root) {
        return checkIteration(root, root);
    }

    private boolean checkIteration(TreeNode p, TreeNode q) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(p);
        queue.offer(q);
        while (!queue.isEmpty()) {
            p = queue.poll();
            q = queue.poll();
            if (p == null && q == null) {
                continue;
            }
            if (p == null || q == null) {
                return false;
            }
            if (p.val != q.val) {
                return false;
            }

            queue.offer(p.left);
            queue.offer(q.right);

            queue.offer(p.right);
            queue.offer(q.left);
        }
        return true;
    }
}
